<template>
  <span>
    <el-upload :class="{'hide-update': limit === value.length}" :list-type="listType" :action="action" :accept="accept"
               :fileList="fileList" :data="formData" :limit="limit" :before-upload="beforeUpload"
               :before-remove="remove" :on-success="success" :on-preview="preview" :multiple="false">
      <i v-if="listType !== 'text'" class="el-icon-upload"></i>
      <el-button type="primary" v-if="listType === 'text' ">上传</el-button>
      <el-dialog append-to-body :visible.sync="dialogVisible">
        <img v-if="preUrl" width="100%" :src="preUrl" alt="">
        <el-button @click="confirm" v-if="showbtn" class="my-btn" type="primary" style="float: left">设置为封面</el-button>
        <el-button v-if="showbtn" @click="changeSwiper('left')" type="warning" plain icon="el-icon-arrow-left"
                   class="left-btn"></el-button>
        <el-button v-if="showbtn" @click="changeSwiper('right')" type="warning" plain icon="el-icon-arrow-right"
                   class="right-btn"></el-button>
      </el-dialog>
    </el-upload>
    <em class="tip">{{ tip }}</em>
  </span>
</template>

<script>
  // import md5 from 'blueimp-md5'
  import {aliToken} from '@/api/uploadToken'
  import SparkMD5 from 'spark-md5'

  export default {
    props: {
      value: {
        type: Array,
        default() {
          return []
        }
      },
      tip: {
        type: String,
        default: ''
      },
      limit: {
        type: Number,
        default: 1
      },
      size: {
        type: Number,
        default: 5000
      },
      accept: {
        type: String,
        default: 'image/png, image/jpeg, image/gif'
      },
      module: {
        type: String,
        default: ''
      },
      showbtn: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const isDev = process.env.NODE_ENV === 'development'
      return {
        action: isDev ? 'https://halo-test.oss-cn-hangzhou.aliyuncs.com/' : 'https://flash-wedding.oss-cn-hangzhou.aliyuncs.com/',
        base_url: '',
        formData: {},
        preUrl: '',
        dialogVisible: false,
        confirmData: {}
      }
    },
    computed: {
      listType() {
        return this.accept === 'image/png, image/jpeg, image/gif' ? 'picture-card' : 'text'
      },
      fileList() {
        const fileList = JSON.parse(JSON.stringify(this.value))
        fileList.forEach((item, key) => {
          item.name = `${key}${item.path}`
          item.key = key
        })
        return fileList
      }
    },
    methods: {
      changeSwiper(direction) {
        let index = this.confirmData.name
        const len = this.fileList.length
        if (direction === 'left') {
          index <= 0 ? index = len - 1 : index -= 1
        } else {
          index >= len - 1 ? index = 1 : index += 1
        }
        this.confirmData = this.fileList[index]
        this.preUrl = this.confirmData.url
      },
      confirm() {
        this.$emit('confirm', this.confirmData)
      },
      getName(file) {
        return new Promise(resolve => {
          const {name} = file
          const suffix = name.substr(name.lastIndexOf('.'))
          const spark = new SparkMD5.ArrayBuffer()

          const reader = new FileReader()
          reader.readAsArrayBuffer(file)
          this.$indicator.open() // loading 文件过大的时候读取时间非常长
          reader.addEventListener('load', (e) => {
            spark.append(e.target.result)
            this.$indicator.close()
            resolve(spark.end() + suffix) // 文件md5加密，放置重复上传
          })
        })
      },
      async beforeUpload(file) {
        if (file.size / 1000 > this.size) {
          this.$message.warning('图片过大')
          return Promise.reject()
        }
        const name = await this.getName(file)
        // console.log(name)
        const {accessid, callback, dir, host, policy, signature} = await aliToken()
        // const {accessid, callback, host, policy, signature} = await aliToken()
        this.action = host
        // this.formData['key'] = `${dir}${md5(file.name)}${file.name.substr(file.name.indexOf('.'))}`
        this.formData['key'] = `${dir}${name}`
        // console.log(this.formData, '123')
        this.formData['OSSAccessKeyId'] = accessid
        this.formData['policy'] = policy
        this.formData['Signature'] = signature
        this.formData['callback'] = callback
        return true
      },
      change(value) {
        this.$emit('change', value)
      },
      remove(file) {
        const value = this.fileList.filter((item, key) => key !== file.key)
        this.$emit('input', value)
        this.change(value)
      },
      success(data) {
        const {base_url, path, id, width, height} = data
        const url = base_url + path + '-300x300'
        const value = [...this.value, {url, path, id, width, height}]
        this.$emit('input', value)
        this.change(value)
      },
      preview(file) {
        if (this.listType !== 'text') {
          this.confirmData = file
          this.preUrl = file.url
          this.dialogVisible = true
        } else {
          console.log(file.url)
          window.open(file.url)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  /*.tip {*/
    /*color: #f0ad4e;*/
  /*}*/
</style>

<style lang="scss">
  .hide-update .el-upload--picture-card {
    display: none;
  }

  .my-btn {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
  }

  .left-btn {
    height: 30px;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    margin: auto;
  }

  .right-btn {
    height: 30px;
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
  }
</style>
